import type { PaginationProps } from "@pureadmin/table";
import { getDataBySQLDesc } from "@/api/common";
import { type Ref, reactive, ref, onMounted, h } from "vue";
import type { PlusColumn } from "plus-pro-components";
import { ElTreeSelect, ElSelect, ElOption, ElPagination } from "element-plus";

export function useOutsourceData(treeRef: Ref) {
  const form = ref({
    kssj: "",
    jssj: "",
    plbm: "",
    wlbm: ""
    // jhpm: ""
  });

  // 外购品类选项数据
  const plbmOptions = ref({ data: [] });
  // 料件编码选项数据 - 改为简单数组
  const ljbhOptions = ref([]);

  const curRow = ref();
  const dataList = ref([]);
  const treeData = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const treeSearchValue = ref();

  // 物料编号分页相关状态
  const ljbhLoading = ref(false);
  const ljbhPagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  });

  // 存储搜索关键词
  const ljbhKeyword = ref("");

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 定义辅助函数来构建树状结构
  const buildTree = (items: any[], parentId = "") => {
    return items
      .filter(item => item["父品类编码"] === parentId)
      .map(item => ({
        ...item,
        label: item["品类名称"],
        value: item["品类编号"],
        children: buildTree(items, item["品类编号"])
      }));
  };

  // 外购品类远程搜索方法
  const searchOutsource = async (query = "") => {
    const { data } = await getDataBySQLDesc({
      action: "public/get_plxx_cpwg_tree"
    });
    plbmOptions.value.data = buildTree(data);
    form.value.plbm = data.find(el => el["层级"] === "1")?.["品类编号"] || "";
  };

  // 加载料件编号数据
  const loadLjbhData = async (query = "", reset = false) => {
    if (ljbhLoading.value) return;
    if (reset) ljbhPagination.currentPage = 1;

    ljbhLoading.value = true;
    try {
      const { data, total } = await getDataBySQLDesc({
        action: "public/get_wlxx_cpwg",
        jhpm: query,
        pageindex: ljbhPagination.currentPage.toString(),
        pagesize: ljbhPagination.pageSize.toString()
      });
      ljbhOptions.value = data || [];
      ljbhPagination.total = total || 0;
    } catch {
      ljbhOptions.value = [];
      ljbhPagination.total = 0;
    } finally {
      ljbhLoading.value = false;
    }
  };

  function debounce<T extends (...args: any[]) => any>(fn: T, delay = 300): T {
    let timer: ReturnType<typeof setTimeout> | null = null;
    return ((...args: Parameters<T>) => {
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        fn(...args);
        timer = null;
      }, delay);
    }) as T;
  }

  /* ---------------- 防抖远程搜索 ---------------- */
  const searchOutsource1 = debounce((query = "") => {
    ljbhKeyword.value = query;
    loadLjbhData(query, true);
  }, 300);

  const columns: TableColumnList = [
    {
      label: "订单日期",
      prop: "订单日期",
      minWidth: 160
    },
    {
      label: "料件编号",
      prop: "料件编号",
      minWidth: 200
    },
    {
      label: "品名",
      prop: "品名",
      minWidth: 200
    },

    {
      label: "规格",
      prop: "规格",
      minWidth: 300
    },
    {
      label: "供应商",
      prop: "供应商",
      minWidth: 260
    },
    {
      label: "采购单价",
      prop: "采购单价",
      minWidth: 160
    },
    {
      label: "采购数量",
      prop: "采购数量",
      minWidth: 160
    },
    {
      label: "采购金额",
      prop: "采购金额",
      minWidth: 160
    },
    {
      label: "采购单位",
      prop: "采购单位",
      minWidth: 160
    },
    {
      label: "销售单位",
      prop: "销售单位",
      minWidth: 160
    },
    {
      label: "销售单价",
      prop: "销售单价",
      minWidth: 100
    },
    {
      label: "订单数量",
      prop: "订单数量",
      minWidth: 160
    },
    {
      label: "订单金额",
      prop: "订单金额",
      minWidth: 160
    },
    {
      label: "发货数量",
      prop: "发货数量",
      minWidth: 160
    },
    {
      label: "销售单位",
      prop: "销售单位",
      minWidth: 160
    },
    {
      label: "进销差价",
      prop: "进销差价",
      minWidth: 160
    },
    {
      label: "进销差额（订）",
      prop: "进销差额（订）",
      minWidth: 160
    },
    {
      label: "进销差额（发）",
      prop: "进销差额（发）",
      minWidth: 160
    }
  ];

  const search_columns: PlusColumn[] = [
    {
      label: "外购品类",
      prop: "plbm",
      valueType: "cascader",
      fieldProps: {
        placeholder: "请选择外购品类"
      },
      renderField(value, onChange) {
        return h(ElTreeSelect as any, {
          data: plbmOptions.value.data,
          filterable: true,
          clearable: true,
          checkStrictly: true,
          modelValue: form.value.plbm,
          "onUpdate:modelValue": (val: any) => {
            onChange && onChange(val);
          }
        });
      }
    },
    {
      label: "料件编号",
      prop: "jhpm",
      valueType: "select",
      fieldProps: {
        filterable: true,
        remote: true,
        placeholder: "请输入关键词搜索",
        loading: ljbhLoading.value
      },
      renderField(value, onChange) {
        return h("div", { class: "pagination-select-container" }, [
          h(
            ElSelect,
            {
              modelValue: value,
              "onUpdate:modelValue": (val: any) => {
                form.value.wlbm = val;
                onChange?.(val);
              },
              filterable: true,
              remote: true,
              loading: ljbhLoading.value,
              placeholder: "请输入关键词搜索",
              remoteMethod: searchOutsource1,
              // 添加以下两个属性以支持手动输入
              // allowCreate: true,
              // defaultFirstOption: true,
              onVisibleChange: (v: boolean) => {
                if (v && ljbhOptions.value.length === 0) searchOutsource1("");
              }
            },
            {
              default: () =>
                ljbhOptions.value.map(item =>
                  h(ElOption, {
                    key: item["料件编号"],
                    label: `${item["品名"]}`,
                    value: item["料件编号"]
                  })
                ),
              footer: () =>
                h(ElPagination, {
                  small: true,
                  layout: "prev, pager, next",
                  pageSize: ljbhPagination.pageSize,
                  currentPage: ljbhPagination.currentPage,
                  total: ljbhPagination.total,
                  onCurrentChange: (p: number) => {
                    ljbhPagination.currentPage = p;
                    loadLjbhData(ljbhKeyword.value, false);
                  },
                  class: "pagination-footer"
                })
            }
          )
        ]);
      }
    },
    {
      label: "订单开始时间",
      prop: "kssj",
      valueType: "date-picker",
      fieldProps: {
        placeholder: "请选择订单开始时间",
        format: "YYYY-MM-DD",
        valueFormat: "YYYY-MM-DD",
        type: "date",
        clearable: true,
        editable: false,
        prefixIcon: "el-icon-date",
        disabledDate: date => date && date > Date.now()
      }
    },
    {
      label: "订单结束时间",
      prop: "jssj",
      valueType: "date-picker",
      fieldProps: {
        placeholder: "请选择订单结束时间",
        format: "YYYY-MM-DD",
        valueFormat: "YYYY-MM-DD",
        type: "date",
        clearable: true,
        editable: false,
        prefixIcon: "el-icon-date",
        disabledDate: date => date && date > Date.now()
      }
    }
  ];

  const handleChange = (values: any) => {
    console.log(values, "change");
  };

  const handleSearch = async (values: any) => {
    await onSearch();
  };

  const handleReset = () => {
    form.value.kssj = "";
    form.value.jssj = "";
    form.value.plbm = "";
    form.value.wlbm = "";
    searchOutsource("");
    onSearch();
  };

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  const fetchParams = async (
    hsmc: string
  ): Promise<Record<string, string[]>> => {
    const params = { action: "public/get_bi_sjfw", hsmc };
    const { data } = await getDataBySQLDesc(params);

    return data.reduce((acc, item) => {
      acc[item["参数编码"]] = item["参数值"];
      return acc;
    }, {});
  };

  async function onSearch() {
    loading.value = true;
    try {
      // 创建一个新的表单对象，包含拼接了时间的日期
      const formData = {
        ...form.value,
        kssj: form.value.kssj ? `${form.value.kssj} 00:00:00` : "",
        jssj: form.value.jssj ? `${form.value.jssj} 59:59:59` : ""
      };
      const params = await fetchParams("get_yf_cpwg_jxmx");
      const { data } = await getDataBySQLDesc({
        action: "biz/reports/get_yf_cpwg_jxmx",
        ...params,
        ...formData,
        // 添加料件编号作为查询条件
        wlbm: form.value.wlbm || undefined
      });
      dataList.value = data || [];
      pagination.total = data?.length || 0;

      setTimeout(() => {
        loading.value = false;
      }, 500);
    } catch (error) {
      loading.value = false;
    }
  }

  onMounted(async () => {
    await searchOutsource("");
    onSearch();
  });

  return {
    form,
    isShow,
    curRow,
    loading,
    columns,
    dataList,
    treeData,
    isLinkage,
    pagination,
    treeSearchValue,
    onSearch,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    search_columns,
    handleChange,
    handleSearch,
    handleReset
  };
}
